// 定义和用户相关的接口
const Router = require('koa-router')
const router = new Router()
const {
    userLogin,
    userRegister,
} = require('../controllers/index.js')
const { sign } = require('../utils/jwt.js')


router.prefix('/user')

router.post('/login', async (ctx, next) => {
    const { username, password } = ctx.request.body // post请求的数据
    // console.log(username, password);
    const res = await userLogin(username, password)
    // console.log(res);

    try {
        if (res.length) {
            const data = {
                username: res[0].username,
                id: res[0].id,
                nickname: res[0].nickname
            }
            const token = sign({
                id: res[0].id,
                username: res[0].username,
                nickname: res[0].nickname,
            })
            // console.log(token);

            ctx.body = {
                code: 200,
                data: data,
                msg: '登陆成功',
                token: token
            }
        } else {
            ctx.body = {
                code: 500,
                msg: '账号或密码错误',
            }
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            data: error,
            msg: '服务器异常',
        }
    }

})

router.post('/register', async (ctx, next) => {
    const { username, password } = ctx.request.body // post请求的数据
    // console.log(username, password);
    const res = await userRegister(username, password)
    console.log(res);

    try {
        if (res.affectedRows) {
            ctx.body = {
                flag: true,
                code: 200,
                msg: '注册成功',
            }
        } else {
            ctx.body = {
                flag: false,
                code: 200,
                msg: '不能重复注册同一个账号',
            }
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            data: error,
            msg: '服务器异常',
        }
    }

})



module.exports = {
    userRouter: router
}

